#include "handwidget.h"
#include "ui_handwidget.h"


HandWidget::HandWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::HandWidget)
{
    ui->setupUi(this);
    init();
    db_init();
    db_select();

    ui->lcdNumber_12->display(m_tm);
    ui->lcdNumber_15->display(m_hm);
    ui->lcdNumber_18->display(m_ill);
    //控制
    ui->label->installEventFilter(this);
    ui->label_2->installEventFilter(this);
    ui->label_3->installEventFilter(this);
    ui->label_4->installEventFilter(this);
    ui->label_5->installEventFilter(this);
    ui->label_6->installEventFilter(this);
    //预警值
    //温度
    ui->label_18->installEventFilter(this);
    ui->label_21->installEventFilter(this);
    //湿度
    ui->label_22->installEventFilter(this);
    ui->label_23->installEventFilter(this);
    //光照强度
    ui->label_7->installEventFilter(this);
    ui->label_17->installEventFilter(this);

}

HandWidget::~HandWidget()
{
    db_update_time();
    QString connectionName = "HandWidget"; // 或统一改为"GreenOasisDB"

    // 创建局部作用域确保所有数据库对象先销毁
    {
        QSqlDatabase db = QSqlDatabase::database(connectionName);
        if (db.isOpen()) {
            // 关闭所有未完成的事务[9](@ref)
            if (db.transaction()) db.rollback();
            db.close(); // 显式关闭连接
        }
        // 此处db对象离开作用域自动销毁
    }

    // 安全移除连接（确保无对象依赖）
    if (QSqlDatabase::contains(connectionName)) {
        QSqlDatabase::removeDatabase(connectionName);
    }

    m_Timer.stop();
    delete ui;
}

void HandWidget::db_init() {
    QString connectionName = "HandWidget";
    // 检查连接是否已存在
    if (!QSqlDatabase::contains(connectionName)) {
        QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", connectionName);
        QString dbPath = QCoreApplication::applicationDirPath() + "/object.db";
        db.setDatabaseName(dbPath);
        if (!db.open()) {
            qDebug() << "DB open error:";
            return;
        }
        QSqlQuery query(db); // 显式传递连接对象
        QString sql = "CREATE TABLE IF NOT EXISTS oasis ("
                      "id INTEGER PRIMARY KEY AUTOINCREMENT, "
                      "temperature REAL, "
                      "humidity REAL, "
                      "illumination INTEGER);";
        if (!query.exec(sql)) {
            qDebug() << "Create table error:";
        } else {
            qDebug() << "Table created/verified";
            // 首次运行时插入默认数据
            query.exec("INSERT OR IGNORE INTO oasis (id, temperature, humidity, illumination) VALUES (1, 30.0, 80.0, 400)");
        }

        query.exec("CREATE TABLE IF NOT EXISTS time("
                  "tm_time INTEGER DEFAULT 0, "
                  "hm_time INTEGER DEFAULT 0, "
                  "ill_time INTEGER DEFAULT 0);");

        // 初始化time表数据
        query.exec("INSERT OR IGNORE INTO time (tm_time, hm_time, ill_time) VALUES (0, 0, 0)");
    }
}

bool HandWidget::db_select()
{
    QSqlDatabase db = QSqlDatabase::database("HandWidget");
    if (!db.isOpen()) {
        qDebug() << "DB not open!";
        return false;
    }

    QSqlQuery query(db);
    query.prepare("SELECT * FROM oasis WHERE id = ?"); // 参数化防注入
    query.addBindValue(1); // 绑定参数

    if (!query.exec()) {
        qDebug() << "Select error:";
        return false;
    }

    if (query.next()) {
        // 修正类型转换（REAL字段用toFloat()）
        m_tm = query.value("temperature").toFloat();
        m_hm = query.value("humidity").toFloat();
        m_ill = query.value("illumination").toInt();
    } else {
        qDebug() << "No data found for id=1";
        return false;
    }

    query.exec("SELECT * FROM time LIMIT 1");
    if (query.next()) {
        tm_time = query.value("tm_time").toInt();
        hm_time = query.value("hm_time").toInt();
        ill_time = query.value("ill_time").toInt();
    }
    ui->lcdNumber_13->display(tm_time);
    ui->lcdNumber_16->display(hm_time);
    ui->lcdNumber_19->display(ill_time);
    return true;
}

bool HandWidget::db_update_time()
{
    QSqlDatabase db = QSqlDatabase::database("HandWidget");
    if (!db.isOpen()) return false;

    QSqlQuery query(db);
    query.prepare("UPDATE time SET tm_time=?, hm_time=?, ill_time=?");
    query.addBindValue(tm_time);
    query.addBindValue(hm_time);
    query.addBindValue(ill_time);
    return query.exec();
}

bool HandWidget::eventFilter(QObject *watched, QEvent *event) //过滤器
{
    //温度
    if(watched == ui->label_4){
        if (event->type() == QEvent::MouseButtonPress){
            emit label_4_push();
            //return true;  //过滤
            return false; //不过滤
        }
    }
    else if(watched == ui->label_3){
        if (event->type() == QEvent::MouseButtonPress){
            emit label_3_push();
            //return true;  //过滤
            return false; //不过滤
        }
    }
    else if(watched == ui->label_18){
        if (event->type() == QEvent::MouseButtonPress){
            m_tm = m_tm + 0.5;
            ui->lcdNumber_12->display(m_tm);
            emit label_18_push(m_tm);
            //return true;  //过滤
            return false; //不过滤
        }
    }
    else if(watched == ui->label_21){
        if (event->type() == QEvent::MouseButtonPress){
            m_tm = m_tm - 0.5;
            ui->lcdNumber_12->display(m_tm);
            emit label_21_push(m_tm);
            //return true;  //过滤
            return false; //不过滤
        }
    }
    //湿度
    else if(watched == ui->label_5){
        if (event->type() == QEvent::MouseButtonPress){
            emit label_5_push();
            //return true;  //过滤
            return false; //不过滤
        }
    }
    else if(watched == ui->label_6){
        if (event->type() == QEvent::MouseButtonPress){
            emit label_6_push();
            //return true;  //过滤
            return false; //不过滤
        }
    }
    else if(watched == ui->label_22){
        if (event->type() == QEvent::MouseButtonPress){
            m_hm = m_hm + 1;
            ui->lcdNumber_15->display(m_hm);
            emit label_22_push(m_hm);
            //return true;  //过滤
            return false; //不过滤
        }
    }
    else if(watched == ui->label_23){
        if (event->type() == QEvent::MouseButtonPress){
            m_hm = m_hm - 1;
            ui->lcdNumber_15->display(m_hm);
            emit label_23_push(m_hm);
            //return true;  //过滤
            return false; //不过滤
        }
    }
    //光照强度
    else if(watched == ui->label){
        if (event->type() == QEvent::MouseButtonPress){
            emit label_push();
            //return true;  //过滤
            return false; //不过滤
        }
    }
    else if(watched == ui->label_2){
        if (event->type() == QEvent::MouseButtonPress){
            emit label_2_push();
            //return true;  //过滤
            return false; //不过滤
        }
    }
    else if(watched == ui->label_7){
        if (event->type() == QEvent::MouseButtonPress){
            m_ill = m_ill + 10;
            ui->lcdNumber_18->display(m_ill);
            emit label_7_push(m_ill);
            //return true;  //过滤
            return false; //不过滤
        }
    }
    else if(watched == ui->label_17){
        if (event->type() == QEvent::MouseButtonPress){
            m_ill = m_ill - 10;
            ui->lcdNumber_18->display(m_ill);
            emit label_17_push(m_ill);
            //return true;  //过滤
            return false; //不过滤
        }
    }
    else{

        return QWidget::eventFilter(watched,event);
    }

}

void HandWidget::init()
{
    QString picStyle = "border-image: url(:/new/prefix1/Resource/AutoTop1.png);";
    QString name = "温度监控";
    ui->handBtnTop1->setPicName(picStyle,name);
    ui->handBtnTop1->setIndex(0);
    m_HandBtnMap.insert(name,ui->handBtnTop1);
    //ui->handBtnTop1->setClickedStyle();
    //ui->stackedWidgetHand->setCurrentIndex(0);

    picStyle = "border-image: url(:/new/prefix1/Resource/AutoTop2.png);";
    name = "湿度监控";
    ui->handBtnTop2->setPicName(picStyle,name);
    ui->handBtnTop2->setIndex(1);
    m_HandBtnMap.insert(name,ui->handBtnTop2);

    picStyle = "border-image: url(:/new/prefix1/Resource/AutoTop3.png);";
    name = "光照监控";
    ui->handBtnTop3->setPicName(picStyle,name);
    ui->handBtnTop3->setIndex(2);
    m_HandBtnMap.insert(name,ui->handBtnTop3);

    QMap<QString,HandTopBtn*>::iterator item = m_HandBtnMap.begin();
    while (item != m_HandBtnMap.end()) {

        connect(item.value(),&HandTopBtn::sigClicked,[=](QString name)
        {
            QMap<QString,HandTopBtn*>::Iterator itembtn = m_HandBtnMap.begin();
            while (itembtn != m_HandBtnMap.end()) {
                if(itembtn.key() != name)
                {
                    ((HandTopBtn*)(itembtn.value()))->setNormalStyle();
                }
                itembtn++;
            }
            ui->stackedWidgetHand->setCurrentIndex(m_HandBtnMap.value(name)->getIndex());
        });
        item++;
    }
    m_Timer.setInterval(20);

    //启动定时器
    m_Timer.start();

    connect(&m_Timer,&QTimer::timeout,[=](){
        ui->lcdNumber_11->display(n_tm);
        ui->lcdNumber_14->display(n_hm);
        ui->lcdNumber_17->display(n_ill);
        //有效时间
        ui->lcdNumber_13->display(tm_time);
        ui->lcdNumber_16->display(hm_time);
        ui->lcdNumber_19->display(ill_time);
    });
}
